package cn.tedu._03vehicle.controller;

import cn.tedu._03vehicle.base.response.JsonResult;
import cn.tedu._03vehicle.base.response.StatusCode;
import cn.tedu._03vehicle.mapper.UserMapper;
import cn.tedu._03vehicle.pojo.dto.UserLoginParam;
import cn.tedu._03vehicle.pojo.dto.UserRegParam;
import cn.tedu._03vehicle.pojo.entity.User;
import cn.tedu._03vehicle.pojo.vo.UserVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@Slf4j
@EnableKnife4j
@Tag(name = "01-用户管理模块")
@RestController
@RequestMapping("/v1/user")
public class UserController {
    @Autowired
    private UserMapper userMapper;



    @PostMapping("reg")
    @Operation(summary = "用户注册")
    @ApiOperationSupport(order = 10)
    public JsonResult regUser(@RequestBody @Valid UserRegParam userRegParam) {
        log.debug("userRgParam= "+userRegParam);
        String judgementName  = userMapper.judgeName(userRegParam.getUsername());
        if(judgementName == null){
            User user = new User();
            BeanUtils.copyProperties(userRegParam, user);
            user.setCreateTime(new Date());
            user.setUpdateTime(new Date());
            log.debug("user= "+user);
            return userMapper.insertUser(user) > 0 ? JsonResult.ok() : new JsonResult(StatusCode.OPERATION_FAILED);
        }
        return new JsonResult(StatusCode.USERNAME_EXISTS);
    }



    @PostMapping("login")
    @Operation(summary = "用户登录")
    @ApiOperationSupport(order = 20)
    public JsonResult login(@RequestBody UserLoginParam userLoginParam, HttpSession  session){
        log.debug("userLoginParam= "+userLoginParam);
        UserVO userVo = userMapper.selectUserByUsernameAndPassword(userLoginParam);
        if(userVo != null){
            session.setAttribute("user", userVo);
            return JsonResult.ok(userVo);
        }
        return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
    }

    @GetMapping("currentUser")
    @Operation(summary = "获取当前登录用户功能")
    @ApiOperationSupport(order = 30)
    public JsonResult currentUser(HttpSession session){
        UserVO userVo = (UserVO) session.getAttribute("user");
        return JsonResult.ok(userVo);
    }



    @GetMapping("logout")
    @Operation(summary = "用户退出")
    @ApiOperationSupport(order = 40)
    public void logout(HttpSession session){
        session.removeAttribute("user");
    }


























}
